package cn.opencodes.framework.core.shiro;

import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;

import cn.opencodes.framework.core.service.AlphaService;
import cn.opencodes.framework.core.utils.SpringUtils;
import cn.opencodes.framework.core.utils.WebUtils;
import cn.opencodes.framework.core.vo.UserRoot;

/**
 * 认证
 * @author HJ
 */
public class AuthcRealm extends AuthorizingRealm {
	
    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof AuthcTokenBean;
    }

    /**
     * 授权(验证权限时调用)
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
    	//用户权限列表
        Long userId = (Long)principals.getPrimaryPrincipal();
        Set<String> permsSet = SpringUtils.getBean(AlphaService.class).getUserPermissions(userId);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setStringPermissions(permsSet);
        return info;
    }

    /**
     * 认证(登录时调用)
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //AuthcTokenFilter注入了user
    	UserRoot user = WebUtils.getUser();
    	if (user == null) {
    		long userId = Long.parseLong(token.getPrincipal().toString());
    		user = SpringUtils.getBean(AlphaService.class).getUserRootInfo(userId);
		}
        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user.getId(), token.getCredentials(), getName());
        return info;
    }
}
